package cn.zzq.aix.nativeinterface.javareflector;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.ComponentContainer;
import com.google.appinventor.components.runtime.EventDispatcher;
import com.google.appinventor.components.runtime.Form;
import com.google.appinventor.components.runtime.util.YailList;

@DesignerComponent(version = 2, category = ComponentCategory.EXTENSION, description = "Java桥组件，可以帮助用户调用本地的Java方法，"
		+ "获取Java字段，创建Java对象等" + "在AppInventor中与Java交互的高级功能。" + "每个代码块的具体作用注释中都已注明，" + "只需鼠标长放到指定代码块即可显示代码块注释，"
		+ "本组件的作者联系方式：2428698039@qq.com.", iconName = "", nonVisible = true)
@SimpleObject(external = true)
@UsesPermissions(permissionNames = "android.permission.READ_LOGS")
public class JavaReflector extends JavaReflectorBase {

	public JavaReflector(ComponentContainer container) {
		super(container);
	}

	/**
	 * 获取因执行某个对象的某个方法或某个类的静态方法而引发的异常信息
	 * 
	 * @param instance      实例对象，如果为静态方法调用，则为null
	 * @param method        引发异常的方法对象
	 * @param parameters    引发异常的方法参数
	 * @param exception     引发的异常对象
	 * @param exceptionName 引发的异常名
	 */
	@SimpleEvent(description = "")
	public static void Exception(Object instance, Object method, YailList parameters, Object exception,
			String exceptionName) {
		EventDispatcher.dispatchEvent(Form.getActiveForm(), "Exception", instance, method, parameters, exception,
				exceptionName);
	}

	@SimpleEvent(description = "当接口实例被调用,建议使用回调函数代替本事件的功能")
	public void Called(String tag, Object interfaceClass, Object method, String methodName, YailList receivedValues) {
		EventDispatcher.dispatchEvent(this, "Called", tag, interfaceClass, method, methodName, receivedValues);
	}

	private Object interfaceReturnValue = null;

	@SimpleFunction(description = "设置接口的返回值")
	public void SetInterfaceReturnValue(Object interfaceReturnValue) {
		this.interfaceReturnValue = interfaceReturnValue;
	}

	@SimpleFunction(description = "创建一个接口类并注册到Called事件，需要带一个标签方便回调Callbacked事件。注意：建议使用回调函数代替本事件的功能")
	public Object RegisterInterface(final Object interfaceClass, final String tag) {
		return Proxy.newProxyInstance(((Class<?>) interfaceClass).getClassLoader(),
				new Class[] { (Class<?>) interfaceClass }, new InvocationHandler() {

					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						Called(tag, interfaceClass, method, method.getName(), YailList.makeList(args));
						return interfaceReturnValue;
					}
				});
	}

}
